import axios from "axios";
import router from "@/router/index.js";
import Vue from "vue";
Vue.use(router);
// 挂载axios
Vue.prototype.$http = axios;

// 基路径
axios.defaults.baseURL = "http://localhost:8080/";
// axios.defaults.baseURL = "/api";

// 超时
axios.defaults.timeout = 10000;

let that = this;
// 请求拦截
axios.interceptors.request.use(
  function (config) {
    const token = sessionStorage.token;
    // 设置请求头格式
    config.headers["Content-Type"] = "application/json";

    // 如果token存在，则将其放到请求头
    if (token) {
      config.headers.Authorization = token;
    }

    return config;
  },
  function (error) {
    // return Promise.reject(error);
  }
);

// 响应拦截
axios.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    if (error.message === "Network Error") {
      console.log(this.$router.push("/network_error"));
      this.$router.push("/network_error");
    }
    if (error.message.includes("timeout")) {
    }
    // return Promise.reject(error);
  }
);
